/**
 * 总编室编单中公共业务逻辑。统一抽取出来，供总编室和播出串联单混入使用
 * author: luanzg
 * date: 20210427
 */
import MessageBox from '@/common/message-box/index.js' // 导入自定义的messagebox 插件

// 节目素材来源转换为编单节目数据，函数配置
const DataTransferFuns = {
  matlib: 'matTransfer', // 素材库来源节目转换函数
  pgmlib: 'PgmTransfer', // 节目库来源节目转换函数
  pgmgrplib: 'PgmgrpTransfer' // 节目组来源转换函数
}

export default {
  provide() {
    return {
      editroom: this
    }
  },
  methods: {
    // 取消表格列表项选中状态
    handleClosereset() {
      this.handleCurrentRow = {} // 清空选中项
      this.$refs.table.setCurrentRow([])
    },

    // 表格单元行选中
    handleCheckRows(row, column, event) {
      // console.log('abc')
      this.handleCurrentRow = row
      // 阻止点击事件再向上层冒泡
      event.stopPropagation()
    },

    // 监听列表工具栏 刷新点击事件
    refreshClick() {
      // window.location.reload()
      this.handleClosereset()
      // this.$refs.table.setCurrentRow([])
      this.getpgmdateDetail()
    },

    // 无保存提示清除列表
    notTipClearlist() {
      this.matlists = []
      this.handleCurrentRow = {}
      this.$nextTick(() => {
        this.pgmlistSave = false
      })
    },

    // 节目从弹窗中替换事件回调
    async pgmReplaceChange(sourceRow, source) {
      if (this.pgmdateCurr.check_flag === 1) return this.$message.error('该节目单已审核通过！不能修改')
      if (DataTransferFuns[source] === undefined) return this.$message.error('来源节目缺少转换函数！')

      // 如果接受的是数组
      const Targetdata = []
      let tmp_pgmlen // 节目长度临时存储
      if (sourceRow instanceof Array) { // 返回的是数组形式
        for (const item of sourceRow) {
          Targetdata.push(this[DataTransferFuns[source]](item))
        }
      } else {
        Targetdata[0] = this[DataTransferFuns[source]](sourceRow)
      }

      if (Targetdata[0].pgm_len !== this.handleCurrentRow.pgm_len) {
        const updatePgmLen = await MessageBox.alert(
          '素材和节目长度不一致，需要更新长度吗？',
          {
            confirmButtonText: '是',
            negateButtonText: '否',
            showCancelButton: true,
            showNegateButton: true,
            cancelButtonText: '取消',
            customClass: 'zdyconfirm',
            closeOnClickModal: false,
            type: 'warning'
          }
        ).catch(err => err)

        if (updatePgmLen === 'cancel') return

        if (updatePgmLen === 'confirm') { // 是
          tmp_pgmlen = Targetdata[0].pgm_len
        } else if (updatePgmLen === 'negate') { // 否
          tmp_pgmlen = this.handleCurrentRow.pgm_len
        }
      }

      const confirmRes = await MessageBox.alert(
        `替换所有素材ID相同的节目[${this.handleCurrentRow.pgm_name}](mat_id=${this.handleCurrentRow.mat_id})吗？`,
        '提示',
        {
          confirmButtonText: '是',
          negateButtonText: '否',
          showCancelButton: true,
          showNegateButton: true,
          cancelButtonText: '取消',
          customClass: 'zdyconfirm',
          closeOnClickModal: false,
          type: 'warning'
        }).catch(err => err)

      if (confirmRes === 'cancel') return // 取消
      Targetdata.forEach(item => {
        item.pgm_len = tmp_pgmlen
      })

      if (confirmRes === 'confirm') { // 是
        // 替换所有列表中素材ID相同的节目
        const searchItems = this.matlists.filter((el, i) => {
          return !!((el.mat_id === this.handleCurrentRow.mat_id && el.pgm_name === this.handleCurrentRow.pgm_name))
        })

        // 使用超时调用对dom异步更新
        const updateReplace = () => {
          if (searchItems.length > 0) {
            const item = searchItems.pop()

            // 继承播出方式
            const target = JSON.parse(JSON.stringify(Targetdata[0]))
            target.play_mode = item.play_mode
            target.ins_mode = item.ins_mode

            item.index > -1 ? this.matlists.splice(item.index, 1, target) : this.matlists.push(target) // 替换当前节目
            this.$nextTick(updateReplace, 20)
          }
        }
        this.$nextTick(updateReplace, 20)
        // 全局替换
      } else if (confirmRes === 'negate') { // 否
        // 只替换当前节目
        const _tempindex = this.matlists.indexOf(this.handleCurrentRow)

        // 继承播出方式
        const target = JSON.parse(JSON.stringify(Targetdata[0]))
        target.play_mode = this.handleCurrentRow.play_mode
        target.ins_mode = this.handleCurrentRow.ins_mode

        _tempindex > -1 ? this.matlists.splice(_tempindex, 1, target) : this.matlists.push(target) // 替换当前节目
      }
    },
    // 节目从弹窗拖拽，插入事件回调
    dragAcceptRows(sourceRow, source) {
      if (this.pgmdateCurr.check_flag === 1) return this.$message.error('该节目单已审核通过！不能修改')
      if (DataTransferFuns[source] === undefined) return this.$message.error('来源节目缺少转换函数！')

      // 统一将接收来的节目转为数组
      const Targetdata = []
      if (sourceRow instanceof Array) { // 返回的是数组形式
        for (const item of sourceRow) {
          Targetdata.push(this[DataTransferFuns[source]](item))
        }
      } else {
        Targetdata[0] = this[DataTransferFuns[source]](sourceRow)
      }

      if (this.dragInsetIndex === undefined) { // 按钮点击方式
        const _tmpindex = this.matlists.indexOf(this.handleCurrentRow) // 查看父列表 是否选中节点
        _tmpindex > -1 ? this.matlists.splice(_tmpindex, 0, ...Targetdata) : this.matlists.push(...Targetdata)
      } else { // 拖拽方式
        this.matlists.splice(this.dragInsetIndex, 0, ...Targetdata)
      }

      this.dragInsetIndex = undefined // 重置事件
    },
    // 素材到编单节目转换
    matTransfer(sourceRow) {
      const targetRow = {}
      let s_time

      if (this.dragInsetIndex === 0) {
        s_time = this.start_s_time || 0
      }
      targetRow.pgmlist_id = this.pgmdateCurr.value
      targetRow.s_time = s_time || 0
      targetRow.grp_flag = 0
      targetRow.pgm_id = ''
      targetRow.play_num = 0
      targetRow.pgm_name = sourceRow.mat_name
      targetRow.pgm_len = sourceRow.file_len
      targetRow.play_mode = 1 // 顺序
      targetRow.ins_mode = 0
      targetRow.pgm_type = sourceRow.mat_type
      targetRow.sign_src = 0
      targetRow.mat_id = sourceRow.mat_id
      targetRow.tape_markin = 0
      targetRow.tape_markout = sourceRow.file_len - 1
      targetRow.start_date = sourceRow.s_date // 首播日期
      return targetRow
    },
    // 节目组到编单转换
    PgmgrpTransfer(sourceRow) {
      const targetRow = {}
      let s_time

      if (this.dragInsetIndex === 0) {
        s_time = this.start_s_time || 0
      }

      targetRow.pgmlist_id = this.pgmdateCurr.value
      targetRow.s_time = s_time
      targetRow.grp_flag = 2
      targetRow.pgm_id = sourceRow.pgmgrp_id
      targetRow.play_num = 0
      targetRow.pgm_name = sourceRow.pgmgrp_name
      targetRow.pgm_len = sourceRow.pgmgrp_len
      targetRow.play_mode = 1 // 顺序
      targetRow.ins_mode = 0
      targetRow.pgm_type = 0
      targetRow.sign_src = 0
      targetRow.mat_id = ''
      targetRow.tape_markin = 0
      targetRow.tape_markout = sourceRow.pgmgrp_len - 1

      return targetRow
    },
    // 接受节目库拖拽返回节点
    PgmTransfer(sourceRow) {
      const targetRow = {}
      let s_time

      if (this.dragInsetIndex === 0) {
        s_time = this.start_s_time || 0
      }

      targetRow.pgmlist_id = this.pgmdateCurr.value
      targetRow.s_time = s_time
      targetRow.grp_flag = 0
      targetRow.pgm_id = sourceRow.pgm_id
      targetRow.play_num = 0
      targetRow.pgm_name = sourceRow.pgm_name
      targetRow.pgm_len = sourceRow.pgm_len
      targetRow.play_mode = 1 // 顺序
      targetRow.ins_mode = 0
      targetRow.pgm_type = 0
      targetRow.sign_src = 0
      targetRow.mat_id = ''
      targetRow.tape_markin = 0
      targetRow.tape_markout = sourceRow.pgm_len - 1

      // 插入拖拽节点下标位置
      return targetRow
    },

    // 计算编单节目的播出时间方法。
    computedPlayTime(lists, index) {
      let p_time
      const nowPgm = lists[index]

      if (nowPgm.play_mode === 3) { // 插播
        p_time = this.insertPlay(lists, nowPgm.ins_mode, index, nowPgm.s_time) // 计算插播节目的播出时间
      } else if (nowPgm.play_mode === 0) { // 定时
        p_time = nowPgm.s_time
      } else if ([1, 2].includes(nowPgm.play_mode)) { // 顺序 ,触发
        p_time = this.sortPlay(lists, index, 0)
        this.$set(nowPgm, 's_time', p_time) // 变更开始时间
      }
      return p_time
    },
    // 顺序，触发播放时间计算
    sortPlay(lists, index, sum = 0) {
      if (index < 0) return sum
      index--
      const lastPgm = lists[index]

      if (index < 0) { // 第一条节目
        return lists[0].s_time
      } else {
        if ([0, 1, 2].includes(lastPgm.play_mode) || index === 0) {
          sum += lastPgm.s_time + lastPgm.pgm_len
          return sum
        } else { // 插播
          sum += lastPgm.pgm_len
          return this.sortPlay(lists, index, sum)
        }
      }
    },
    // 插播时间计算方法
    insertPlay(lists, ins, index, sum = 0) {
      if (index < 0) return sum
      index--
      let lastPgm

      if (ins === 0) { // 相对
        if (index < 0) { // 第一条节目了
          return lists[0].s_time
        } else if (index === 0) {
          lastPgm = lists[0]
          return sum + ([0, 1, 2].includes(lastPgm.play_mode) ? lastPgm.s_time : lastPgm.s_time + lastPgm.pgm_len)
        } else {
          lastPgm = lists[index]
          if ([0, 1, 2].includes(lastPgm.play_mode)) {
            sum += lastPgm.s_time
            return sum
          } else { // 插播
            sum += lastPgm.pgm_len
            return this.insertPlay(lists, ins, index, sum)
          }
        }
      } else if ([1, 3].includes(ins)) { // 绝对, 手插
        return lists[index + 1].s_time
      } else if (ins === 2) { // 跟插
        if (index < 0) {
          return lists[0].s_time
        } else {
          lastPgm = lists[index]
          if ([0, 1, 2].includes(lastPgm.play_mode)) {
            sum += lastPgm.s_time
            return sum
          } else { // 插播
            return lastPgm.s_time_play + lastPgm.pgm_len
          }
        }
      }
    }
  }
}
